<template>
  <div class="hello">
    
      <div class="table">
        <mt-tabbar v-model="active">
          <mt-tab-item id="上传发票">
            <img slot="icon" v-show="active=='发票夹'" src="../assets/上传（未选中状态）.svg">
            <img slot="icon" v-show="active=='上传发票'" src="../assets/上传发票（选中状态）.svg">
            上传发票
          </mt-tab-item>
          <mt-tab-item id="发票夹">
            <img slot="icon" v-show="active=='上传发票'"  src="../assets/票夹（未选中状态） copy.svg">
            <img slot="icon" v-show="active=='发票夹'"  src="../assets/票夹（选中状态）.svg">
            发票夹
          </mt-tab-item>
        </mt-tabbar>
        <mt-tab-container v-model="active">
          <mt-tab-container-item id="上传发票">
            <div class="buttonBox" :style="{marginTop:heightVal/4+'px'}">
                <mt-button class="buttonQR" type="danger" style="coloc:#96CF61" @click="scanQRCode" size="large">扫码上传</mt-button>
                <mt-button class="buttonEnter" type="primary" @click="enteringFactor" size="large">录入要素上传</mt-button>
            </div>
          </mt-tab-container-item>
          <mt-tab-container-item id="发票夹">
            <div class="invoiceClip">
                <invoice-clip @invoiceDataVal="invoiceDataValFun" :activeChange="activeChange" :userId="userId"></invoice-clip>
            </div>
          </mt-tab-container-item>
        </mt-tab-container>
      </div>

      <mt-actionsheet
        :actions="actions"
        v-model="sheetVisible">
      </mt-actionsheet>

  </div>
</template>

<script>
import axios from 'axios'
import { Button } from 'mint-ui';
import { Actionsheet } from 'mint-ui';
import Bus from '@/bus.js'
import invoiceClip from '@/components/InvoiceClip.vue'

export default {
  data () {
    return {
      heightVal:'',
      selected:'',
      times:'',
      noncestr:'',
      signature:'',
      invoiceInfor:'',
      active:'',
      invoiceDataVal:{},
      invoiceType:'',
      userId:'',
      type:'',
      invoicedigest:'',
      activeChange:false,
      clickStyle:'',
      invoice:'',
      actions:[],
      // actions:['增值税专用发票','增值税普通发票','增值税普通发票（电子）','增值税普通发票（卷式）','通行费发票'],
      sheetVisible:false,
    }
  },
  created () {
    var self = this;
    this.userId = this.$route.params.userId;
    this.type = this.$route.params.type;
    this.heightVal = window.screen.availHeight;
    if(this.type == '1'){
      this.active='上传发票';
    }else if(this.type == '2'){
      this.active='发票夹';
    }
    this.actions = [
      {name:'增值税专用发票',method(){self.invoiceType='01';self.closeSelect(self.invoiceType);}},
      {name:'增值税普通发票',method(){self.invoiceType='04';self.closeSelect(self.invoiceType);}},
      {name:'增值税普通发票(电子)',method(){self.invoiceType='10';self.closeSelect(self.invoiceType);}},
      {name:'增值税普通发票(卷式)',method(){self.invoiceType='11';self.closeSelect(self.invoiceType);}},
      {name:'通行费发票',method(){self.invoiceType='14';self.closeSelect(self.invoiceType);}},
      {name:'通用机打发票',method(){self.invoiceType='T1';self.closeSelect(self.invoiceType);}}
    ]
  },
  watch:{
    active(newVal){
      if(newVal == '发票夹'){
        this.activeChange = true;
      }
    },
  },
  beforeDestroy () {
    console.log(this.invoiceDataVal)
      Bus.$emit('invoiceDataVal',this.invoiceDataVal);
      // Bus.$emit('invoicedigest',this.invoicedigest);
  },
  methods:{
    scanQRCode(){  //扫码上传页面
        this.sheetVisible = true;
        this.clickStyle = 'scanQRCode';
    },
    invoiceDataValFun(value){
      this.invoiceDataVal = value;
    },
    enteringFactor(){  //录入要素页面
        this.sheetVisible = true;
        this.clickStyle = 'enteringFactor';

        // this.$router.push({path:'/enteringFactor/'+this.userId});
    },
    closeSelect(val){
      if(this.clickStyle == 'scanQRCode'){
          this.getJsApiTicket();
      }else if(this.clickStyle == 'enteringFactor'){
          this.$router.push({path:'/enteringFactor/'+this.userId+'/'+this.invoiceType});
      }
    },
    getJsApiTicket(){
        var self = this;
        axios({
          headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
          method: 'get',
          url: '/wechatInvoice/wechat/getTokenAndTicket.do',
          params: {
            data: (() => {
              let obj = {
              }
              Object.assign(obj, this.searchObj)
              return JSON.stringify(obj);
            })()
          }
        }).then((rep) => {
          self.times=rep.data.data.timeStamp;
          self.noncestr=rep.data.data.nonceStr;
          self.signature=rep.data.data.sigStr;
          self.JSCode();
        }, (rep) => { });

    },
    requestInfo(){
      if(this.invoiceInfor.split(",")[1] == '11'){
          alert('识别失败，请手动录入');
      }else if(this.invoiceInfor.split(",")[1] == ''){
          this.invoiceInfor.split(",")[1] = this.invoiceType;
          var self = this;
          axios({
            headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
            method: 'get',
            url: '/wechatInvoice/invoice/rec.do',
            params: {
              data: (() => {
                let obj = {
                  invoiceContent:this.invoiceInfor
                  // invoiceContent:'01,04,4403174320,02955255,82.18,20180814,43955103043247806871,853F,'
                }
                Object.assign(obj, this.searchObj)
                return JSON.stringify(obj);
              })()
            }
          }).then((rep) => {
            if (rep.data.status === '1') {
              self.invoiceDataVal = rep.data.invoiceData;
              self.$router.push({path:'/InvoiceIdentification/upload/'+self.userId});
            }else{
              alert('识别失败，请手动录入');
            }
          }, (rep) => { 
          });
      }else{
         var self = this;
          axios({
            headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
            method: 'get',
            url: '/wechatInvoice/invoice/rec.do',
            params: {
              data: (() => {
                let obj = {
                  invoiceContent:this.invoiceInfor
                  // invoiceContent:'01,04,4403174320,02955255,82.18,20180814,43955103043247806871,853F,'
                }
                Object.assign(obj, this.searchObj)
                return JSON.stringify(obj);
              })()
            }
          }).then((rep) => {
            if (rep.data.status === '1') {
              self.invoiceDataVal = rep.data.invoiceData;
              self.$router.push({path:'/InvoiceIdentification/upload/'+self.userId});
            }else{
              alert('识别失败，请手动录入');
            }
          }, (rep) => {
           });
      }
    },
    JSCode(){
      var self = this;
        wx.config({
            beta: true,// 必须这么写，否则wx.invoke调用形式的jsapi会有问题
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: 'wx5f80212a4a43a93a', // 必填，企业微信的corpID
            timestamp: self.times, // 必填，生成签名的时间戳
            nonceStr: self.noncestr, // 必填，生成签名的随机串
            signature: self.signature,// 必填，签名，见附录1
            jsApiList: [ 'scanQRCode'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        });
        wx.ready(function(){
            wx.scanQRCode({
                desc: 'scanQRCode desc',
                needResult: 1, // 默认为0，扫描结果由企业微信处理，1则直接返回扫描结果，
                scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                success: function(res) {
                  self.invoiceInfor = res.resultStr;
                  self.requestInfo(res);
                },
                error: function(res) {
                    if (res.errMsg.indexOf('function_not_exist') > 0) {
                        alert('版本过低请升级')
                    }
                }
            });
        });
        wx.error(function(res){
            // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
        });
    },
  },
  components: {
    Bus,
    invoiceClip,
  }
}
</script>

<style  scoped>
.hello{

}
.buttonBox{
  width: 90%;
  margin: 0 auto;
}
.buttonQR{
  margin:20px 0;
}
.buttonEnteraa{
  margin: 20px 0;
}
.invoiceClip{
  height: calc(100%-55px);
}
.mint-tabbar{
  position: fixed
}
</style>
